﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace CS.Utility
{
    public static class Creation
    {

        private static readonly Dictionary<string, Assembly> assemblies = new Dictionary<string, Assembly>(); //程序集集合


        public static Func<T> GetFunc<T>()
        {
            NewExpression newExp = Expression.New(typeof(T));
            Expression<Func<T>> lambdaExp = Expression.Lambda<Func<T>>(newExp, null);
            Func<T> func = lambdaExp.Compile();
            return func;
        }


        public static Func<T> GetFunc<T>(string assemblyName, string typename)
        {
            Assembly assembly;
            if (!assemblies.ContainsKey(assemblyName))
            {
                assembly = Assembly.Load(assemblyName);
                assemblies[assemblyName] = assembly;
            }
            else
            {
                assembly = assemblies[assemblyName];
            }
            Type type = assembly.GetType(typename);
            NewExpression newExp = Expression.New(type);
            Expression<Func<T>> lambdaExp = Expression.Lambda<Func<T>>(newExp, null);
            Func<T> func = lambdaExp.Compile();
            return func;
        }

    }
}